package com.leetcode.partition6;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author `RKC`
 * @date 2021/10/31 9:29
 */
public class LC500键盘行 {

    public static String[] findWords(String[] words) {
        String one = "qwertyuiop", two = "asdfghjkl", three = "zxcvbnm";
        List<String> answer = new ArrayList<>();
        int[][] boardTable = new int[3][123];
        for (int i = 0; i < one.length(); i++) {
            boardTable[0][one.charAt(i)]++;
            boardTable[0][one.charAt(i) - 32]++;
        }
        for (int i = 0; i < two.length(); i++) {
            boardTable[1][two.charAt(i)]++;
            boardTable[1][two.charAt(i) - 32]++;
        }
        for (int i = 0; i < three.length(); i++) {
            boardTable[2][three.charAt(i)]++;
            boardTable[2][three.charAt(i) - 32]++;
        }
        for (String word : words) {
            if (word.length() == 1) {
                answer.add(word);
                continue;
            }
            int[] table = null;
            for (int[] tab : boardTable) {
                if (tab[word.charAt(0)] != 0) {
                    table = tab;
                    break;
                }
            }
            if (table == null) continue;
            //只从table中查找
            for (int i = 1; i < word.length(); i++) {
                if (table[word.charAt(i)] != 0 && i == word.length() - 1) {
                    answer.add(word);
                } else if (table[word.charAt(i)] == 0) {
                    break;
                }
            }
        }
        return answer.toArray(new String[0]);
    }

    public static void main(String[] args) {
        String[] words = {"Hello", "Alaska", "Dad", "Peace"};
        System.out.println(Arrays.toString(findWords(words)));
    }
}
